package com.joshua.spring.integration.authenticator;

import com.joshua.spring.entity.dto.UserInfoDTO;
import com.joshua.spring.entity.dto.UserQueryDTO;
import com.joshua.spring.entity.em.AuthTypeEnum;
import com.joshua.spring.entity.em.ResponseEnum;
import com.joshua.spring.integration.IntegrationAuthentication;
import com.joshua.spring.integration.exception.IntegrationAuthenticationServiceException;
import com.joshua.spring.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;


/**
 * com.joshua.spring.business.integration -- SmsAuthenticator
 * description:
 *
 * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @date 2020/1/6 15:39
 */
@Component
public class SmsAuthenticator extends AbstractIntegrationAuthenticator {

    @Autowired
    private UserService userService;

    @Override
    public UserInfoDTO authenticate(IntegrationAuthentication authentication) {
        String phone = authentication.getAuthParameter("phone");
        if(StringUtils.isEmpty(phone)){
            throw new IntegrationAuthenticationServiceException(ResponseEnum.NULL_PHONE_NUM);
        }
        String code = authentication.getAuthParameter("verifyCode");
        //测试项目，所以将验证码定死为：1234
        if(! "1234".equals(code)){
            throw new IntegrationAuthenticationServiceException(ResponseEnum.ERROR_VERIFY_CODE);
        }
        return userService.queryUser(UserQueryDTO.builder().phone(phone).build());
    }

    @Override
    public boolean support(IntegrationAuthentication authentication) {
        return  AuthTypeEnum.SMS.equals(authentication.getAuthType());
    }
}
